package com.healthcloud.controller.modules.patient;

import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Maps;
import com.healthcloud.annotation.SysLog;
import com.healthcloud.constants.UserConsts;
import com.healthcloud.dao.PpPatientNewaddDao;
import com.healthcloud.dto.req.PatientDataSpecReq;
import com.healthcloud.dto.req.PpPatientBaseReq;
import com.healthcloud.dto.res.CountSpecsRes;
import com.healthcloud.entity.*;
import com.healthcloud.entity.PatientRecord.PatientInfoVo;
import com.healthcloud.entity.PatientRecord.RecordInfoVo;
import com.healthcloud.entity.patient.PatientDataEntity;
import com.healthcloud.entity.patient.PatientDataSpecEntity;
import com.healthcloud.entity.testresult.TestresultVo;
import com.healthcloud.enums.SpecStatusEnum;
import com.healthcloud.exception.ReturnException;
import com.healthcloud.service.*;
import com.healthcloud.service.patient.PatientDataService;
import com.healthcloud.service.patient.PatientDataSpecService;
import com.healthcloud.utils.*;
import com.healthcloud.utils.poi.ExcelUtil;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DateConverter;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;
import com.healthcloud.utils.file.FileUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 病人档案
 *
 * @author yucl
 * @email yucailong1111@126.com
 * @date 2017-09-04 14:03:05
 */
@Controller
@RequestMapping("pppatientbase")
@Slf4j
public class PpPatientBaseController {
    @Autowired
    private PpPatientBaseService ppPatientBaseService;

    @Autowired
    private SysConfigService sysConfigService;

    @Autowired
    private TestresultService testresultService;

    @Autowired
    private TestprojectkindService testprojectkindService;

    @Autowired
    private HlDoctorService hlDoctorService;

    @Autowired
    private HlHospitalService hlHospitalService;

    @Autowired
    private PatientDataService patientDataService;

    @Autowired
    private PatientDataSpecService patientDataSpecService;

    @Autowired
    private PpPatientNewaddDao patientNewaddDao;
    /**
     * 列表
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @RequiresPermissions("patient:list")
    public String list(Model model,
                       @ApiParam(value = "1=高血压人群 2=糖尿病人群", name = "diseasesType")
                       @RequestParam(value = "diseasesType", required = false) String diseasesType) {
        model.addAttribute("diseasesType", diseasesType);
        return "bus/pppatientbase/pppatientbasemgr";
    }

    /**
     * 列表
     */
    @RequestMapping(value = "/toDiseasesList", method = RequestMethod.GET)
    @RequiresPermissions("patient:list")
    public String toDiseasesList(Model model,
                                 @ApiParam(value = "1=高血压人群 2=糖尿病人群 3=高血脂人群 4=骨松人群", name = "diseasesType")
                                 @RequestParam(value = "diseasesType", required = false) String diseasesType) {
        model.addAttribute("diseasesType", diseasesType);
        return "bus/pppatientbase/diseasesPatientMgr";
    }

    /**
     * 列表
     */
    @RequestMapping(value = "/qianhu/toDiseasesList", method = RequestMethod.GET)
    @RequiresPermissions("patient:list")
    public String toQianHuDiseasesList(Model model,
                                       @ApiParam(value = "1=高血压人群 2=糖尿病人群 3=高血脂人群 4=骨松人群", name = "diseasesType")
                                       @RequestParam(value = "diseasesType", required = false) String diseasesType) {
        model.addAttribute("diseasesType", diseasesType);
        return "bus/boneLoose/qianhu/record";
    }

    @ApiOperation(value = "查询病人列表", notes = "查询病人列表")
    @RequestMapping(value = "/queryListBySearch", method = RequestMethod.POST)
    @ResponseBody
    public MsgVo queryListBySearch(PpPatientBaseVo entity,
                                   @ModelAttribute("pageParam") PageParam pageParam) throws Exception {

        String ids = hlHospitalService.getChildeIds();
        if (StringUtils.isNotEmpty(ids)) {
            entity.setHospitalIds(ids);
        }
        List<PpPatientBaseVo> list = ppPatientBaseService.queryListVo(entity, pageParam);
        List<PpPatientBaseExtVo> ppPatientBaseExtVoList = new ArrayList<>();
        int count = ppPatientBaseService.queryTotalVo(entity);

        ConvertUtils.register(new DateConverter(null), java.util.Date.class);
        if (count > 0) {
            for (PpPatientBaseVo ppPatientBaseVo : list) {
                PpPatientBaseExtVo vo = new PpPatientBaseExtVo();
                BeanUtils.copyProperties(vo, ppPatientBaseVo);
                ppPatientBaseExtVoList.add(vo);
            }
        }
        return new MsgVo(ppPatientBaseExtVoList, count, count, pageParam.getsEcho());
    }

    @ApiOperation(value = "根据身份证号，查询建档信息", notes = "根据身份证号，查询建档信息")
    @RequestMapping(value = "/getPpPatientNewadd", method = RequestMethod.GET)
    @ResponseBody
    public ApiRes getPpPatientNewadd(@ApiParam(required = true, value = "身份证号", name = "idCard")
                                @RequestParam("idCard") String idCard) {

        List<PpPatientNewadd> list = patientNewaddDao.queryListByIdCards(idCard);
        HashMap<Object, Object> map = new HashMap<>();
        map.put("list", list);
        return new ApiRes(true, map, "", "");
    }

    @ApiOperation(value = "查询病人列表", notes = "查询病人列表")
    @RequestMapping(value = "/queryListBySearch/{hospitalId}", method = RequestMethod.GET)
    @ResponseBody
    public MsgVo queryListBySearchByHospitalId(PpPatientBaseVo entity,
                                               @ModelAttribute("pageParam") PageParam pageParam,
                                               @PathVariable(value = "hospitalId") String hospitalId) throws Exception {

        entity.setHospitalIds(hospitalId);
        List<PpPatientBaseVo> list = ppPatientBaseService.queryListVo(entity, pageParam);
        List<PpPatientBaseExtVo> ppPatientBaseExtVoList = new ArrayList<>();
        int count = ppPatientBaseService.queryTotalVo(entity);

        ConvertUtils.register(new DateConverter(null), java.util.Date.class);
        if (count > 0) {
            for (PpPatientBaseVo ppPatientBaseVo : list) {
                PpPatientBaseExtVo vo = new PpPatientBaseExtVo();
                BeanUtils.copyProperties(vo, ppPatientBaseVo);
                ppPatientBaseExtVoList.add(vo);
            }
        }
        return new MsgVo(ppPatientBaseExtVoList, count, count, pageParam.getsEcho());
    }

    /**
     * 慈溪访问病人列表接口
     *
     * @param entity
     * @return
     */
    @ApiIgnore
    @RequestMapping(value = "/cx/n/queryList", method = RequestMethod.POST)
    @ResponseBody
    public ApiRes cxQueryListBySearch(PpPatientBaseVo entity,
                                      @ModelAttribute("pageParam") PageParam pageParam) {
        entity.setHospitalIds("10000036");
        List<PpPatientBaseVo> list = ppPatientBaseService.queryListVo(entity, pageParam);
        int count = ppPatientBaseService.queryTotalVo(entity);
        MsgVo msgVo = new MsgVo(list, count, null, null);
        return new ApiRes(msgVo);
    }

    /**
     * 跳转至新增页面
     */
    @ApiOperation(value = "病人信息新增页面", notes = "病人信息新增页面")
    @RequestMapping(value = "/toaddPatient", method = RequestMethod.GET)
    public String toaddPatient() {
        return "admin/archives/addPatient";
    }

    /**
     * 跳转至新增页面-钱湖
     */
    @ApiOperation(value = "病人信息新增页面-钱湖", notes = "病人信息新增页面-钱湖")
    @RequestMapping(value = "/qianhu/toaddPatient", method = RequestMethod.GET)
    public String toaddQianhuPatient() {
        return "bus/boneLoose/qianhu/addPatient";
    }

    /**
     * 删除
     */
    @SysLog("删除PpPatientBase")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @RequiresPermissions("patient:delete")
    @ResponseBody
    public ApiRes delete(Integer[] ids) {
        ppPatientBaseService.deleteBatch(ids);
        return ApiRes.SUCCESS;
    }

    /**
     * ajax验证身份证是否存在
     *
     * @param idcard 身份证地址
     * @reurn true:验证通过
     */
    @RequestMapping(value = "/validateIdcard", method = RequestMethod.POST)
    public @ResponseBody
    Object validateIdcard(String idcard, String exception) {
        Map<String, Boolean> map = new HashMap<>();
        if (idcard != null && exception != null && idcard.trim().equals(exception.trim())) {
            map.put("valid", true);
            return map;
        }
        if (idcard == null || "".equals(idcard.trim())) {
            map.put("valid", false);
            return map;
        }
        PpPatientBaseEntity entity = ppPatientBaseService.queryByIdcard(idcard);
        if (entity == null) {
            map.put("valid", true);
            return map;
        } else {
            map.put("valid", false);
            return map;
        }
    }

    @RequiresPermissions("patient:add")
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public ApiRes upload(@RequestParam(required = false) MultipartFile file, HttpServletRequest request) {
        //拼接保存路径
        String path = request.getServletContext().getRealPath("/") + CommonPath.PATIENT_TEMPLATE;
        File dir = new File(path);
        //成功条数
        int j = 0;

        List<ResultVo> results = new ArrayList<ResultVo>();
        //如果文件夹不存在则创建
        if (!dir.exists() && !dir.isDirectory()) {
            dir.mkdir();
        }
        path += System.currentTimeMillis() + file.getOriginalFilename();
        try {
            File f = FileUtils.saveFile(file, path);
            //解析excel
            List<String[]> datas = ExcelUtils.getData(new FileInputStream(f), 0, 2, 7);

            List<SysConfigEntity> configs = sysConfigService.queryListByName("gender2");
            for (int i = 0; i < datas.size(); i++) {
                PpPatientBaseEntity entity = new PpPatientBaseEntity();
                String[] data = datas.get(i);
                String realname = data[0];
                String gender = data[1];
                String idcard = data[2];
                String medicalinsurancenum = data[3];
                String phone = data[4];
                String height = data[5];
                String weight = data[6];
                //判断必填字段
                //姓名不能为空
                if (StringUtils.isEmpty(realname)) {
                    results.add(new ResultVo(realname, idcard, "姓名不能为空", i + 3));
                    continue;
                }
                if (StringUtils.isEmpty(idcard)) {
                    results.add(new ResultVo(realname, idcard, "身份证不能为空", i + 3));
                    continue;
                }
                PpPatientBaseEntity oldPatient = ppPatientBaseService.queryByIdcard(idcard);
                if (oldPatient != null) {
                    results.add(new ResultVo(realname, idcard, "身份证已存在", i + 3));
                    continue;
                }
                for (SysConfigEntity config : configs) {
                    if (config.getValue().equals(gender)) {
                        entity.setGender(Integer.parseInt(config.getKey()));
                    }
                }
                entity.setRealname(realname);
                entity.setIdcard(idcard);
                entity.setMedicalinsurancenum(medicalinsurancenum);
                entity.setPhone(phone);
                try {
                    entity.setHeight(Double.parseDouble(StringUtils.isEmpty(height) ? "0" : height));
                    entity.setWeight(Double.parseDouble(StringUtils.isEmpty(weight) ? "0" : weight));
                } catch (Exception e) {
                    results.add(new ResultVo(realname, idcard, "身高体重为数字", i + 3));
                    continue;
                }
                entity.setCreateId(ShiroUtils.getUserId());
                entity.setSourceType(1);
                ppPatientBaseService.save(entity);

                j++;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ApiRes(false, null, null, "导入失败");
        }
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("successNum", j);
        dataMap.put("failNum", results.size());
        dataMap.put("results", results);
        return new ApiRes(true, dataMap, null, "导入成功");
    }

    /**
     * 由病人页面跳转至档案页面
     */
    @ApiOperation(value = "跳转档案页", notes = "跳转档案页")
    @RequestMapping(value = "/toArchives", method = RequestMethod.GET)
    public String toArchives(Model model,
                             @ApiParam(value = "1=高血压人群 2=糖尿病人群 3=高血脂人群 4=骨松人群", name = "diseasesType")
                             @RequestParam(value = "diseasesType", required = false) String diseasesType) {
        model.addAttribute("diseasesType", diseasesType);
        return "admin/archives/archives";
    }

    @ApiOperation(value = "病人基本信息", notes = "病人基本信息")
    @RequestMapping(value = {"/patientInfo", "/n/patientInfo", "/cx/n/patientInfo"}, method = RequestMethod.POST)
    @ResponseBody
    public ApiRes patientInfo(@ApiParam(required = true, value = "身份证号", name = "idCard")
                              @RequestParam("idCard") String idCard) {
        return patientInfoVo(idCard);
    }

    @ApiIgnore(value = "病人基本信息")
    public ApiRes patientInfoVo(String idCard) {

        IdcardInfoExtractorUtil id = new IdcardInfoExtractorUtil(idCard);
        String sex = id.getGender();
        if (StringUtils.isNotEmpty(sex) && "1".equals(sex)) {
            sex = "男";
        } else if (StringUtils.isNotEmpty(sex) && "2".equals(sex)) {
            sex = "女";
        }
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");

        PatientInfoVo patientInfoVo = ppPatientBaseService.searchByIdCard(idCard);
        patientInfoVo.setAge(id.getAge());
        patientInfoVo.setBirthday(sf.format(id.getBirthday()));
        patientInfoVo.setSex(sex);
        Double height = Double.valueOf(StringUtils.isEmpty(patientInfoVo.getHeight()) ? "0" : patientInfoVo.getHeight());
        Double weight = Double.valueOf(StringUtils.isEmpty(patientInfoVo.getWeight()) ? "0" : patientInfoVo.getWeight());
        if (height != null && height != 0 && height != null && height != 0) {
            double BMI = weight * 100 * 100 / height / height;
            BigDecimal b = new BigDecimal(BMI);
            patientInfoVo.setBMI(b.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue());
        } else {
            patientInfoVo.setBMI(0.0);
        }
        patientInfoVo.setWeight(patientInfoVo.getWeight() != null ? patientInfoVo.getWeight() : "");
        patientInfoVo.setHeight(patientInfoVo.getHeight() != null ? patientInfoVo.getHeight() : "");
        //慈溪医院才可以同步
        if (patientInfoVo.getHospitalId() != null && patientInfoVo.getHospitalId() == 10000036l) {
            patientInfoVo.setSynchronizationType(1);
        }
        return new ApiRes(true, patientInfoVo, "", "");
    }

    @ApiOperation(value = "根据身份证号，查询特殊处理备注", notes = "根据身份证号，查询特殊处理备注")
    @RequestMapping(value = "/getSpecRemark", method = RequestMethod.POST)
    @ResponseBody
    public ApiRes getSpecRemark(@ApiParam(required = true, value = "身份证号", name = "idCard")
                                @RequestParam("idCard") String idCard) {
        // 根据身份证号，查询特殊处理备注
        String specRemark = patientDataService.getSpecRemarkByIdCard(idCard);
        Map<String, Object> map = Maps.newHashMap();
        map.put("specRemark", null != specRemark ? specRemark : "");
        return new ApiRes(true, map, "", "");
    }

    @ApiOperation(value = "血压信息", notes = "血压信息")
    @RequestMapping(value = "/BpInfo", method = RequestMethod.POST)
    @ResponseBody
    public ApiRes BpInfo(@ApiParam(required = true, value = "身份证号", name = "idCard")
                         @RequestParam("idCard") String idCard,
                         @ApiParam(value = "起始时间", name = "beginTime")
                         @RequestParam(value = "beginTime", required = false) String beginTime,
                         @ApiParam(value = "截止时间", name = "endTime")
                         @RequestParam(value = "endTime", required = false) String endTime,
                         PageParam pageParam) {
        List<TestresultEntity> testresultEntityList = testresultService.queryLastBp(idCard);
        PatientInfoVo patientInfoVo = ppPatientBaseService.searchByIdCard(idCard);
        if (testresultEntityList == null) {
            return new ApiRes(false, null, "身份证号有误", "身份证号有误");
        }
        Map<String, String> lastInfo = new HashMap<>();
        for (TestresultEntity entity : testresultEntityList) {
            lastInfo.put("testItemCode_" + entity.getTestItemCode(), entity.getTestValue());
        }
        String[] time = testresultService.queryListTime(idCard, beginTime, endTime, pageParam);
        if (time.length == 0) {
            Map<String, Object> resultmap = new HashMap<>();
            resultmap.put("bpList", null);
            resultmap.put("iTotalDisplayRecords", 0);
            return new ApiRes(true, resultmap, "暂无数据", "暂无数据");
        }
        List<TestresultEntity> list = testresultService.queryByListTime(idCard, time);
        // int iTotalDisplayRecords = list.size(); // 当前页展示的记录数

        // 根据身份证号、开始时间和结束时间，列表查询测试时间
        String[] testTimes = testresultService.listTestTimeByIdCardAndTime(idCard, beginTime, endTime); // update by liujx 2019-08-27
        int iTotalRecords = testresultService.countByListTime(idCard, testTimes); // 总记录数

        Map<String, Object> map = new HashMap<>();
        map.put("bpInfo", patientInfoVo);
        map.put("ssyValue", lastInfo.get("testItemCode_104001") == null ? "" : lastInfo.get("testItemCode_104001"));
        map.put("szyValue", lastInfo.get("testItemCode_104002") == null ? "" : lastInfo.get("testItemCode_104002"));
        map.put("heartRate", lastInfo.get("testItemCode_104003") == null ? "" : lastInfo.get("testItemCode_104003"));
        map.put("bpList", list);
        map.put("iTotalDisplayRecords", iTotalRecords);
        return new ApiRes(true, map, "", "");
    }

    @ApiOperation(value = "统计近一个月每天的特殊处理患者人数", notes = "统计近一个月每天的特殊处理患者人数")
    @RequestMapping(value = "/countSpecsLastMonth", method = RequestMethod.GET)
    @ResponseBody
    public ApiRes countSpecsLastMonth() {
        String ids = hlHospitalService.getChildeIds();
        List<CountSpecsRes> list = patientDataService.countSpecsLastMonth(ids);
        Map<String, Object> map = Maps.newHashMap();
        map.put("countSpecList", list);
        return new ApiRes(true, map, "", "");
    }

    @ApiOperation(value = "统计近每个月特殊处理患者人数", notes = "统计近每个月特殊处理患者人数")
    @RequestMapping(value = "/countSpecsPerMonth", method = RequestMethod.GET)
    @ResponseBody
    public ApiRes countSpecsPerMonth(String year) {
        String ids = hlHospitalService.getChildeIds();
        List<CountSpecsRes> list = patientDataService.countSpecsPerMonth(ids, year);
        return new ApiRes(true, list, "", "");
    }

    @ApiOperation(value = "按天取平均值列表", notes = "按天取平均值列表")
    @RequestMapping(value = "/resultAvgByDay", method = RequestMethod.POST)
    @ResponseBody
    public ApiRes resultAvgByDay(@ApiParam(required = true, value = "身份证号", name = "idCard")
                                 @RequestParam("idCard") String idCard,
                                 @ApiParam(required = true, value = "时间 week month quarter year", name = "date")
                                 @RequestParam(value = "date", required = false) String date,
                                 @ApiParam(required = true, value = "血压 104001,104002 血糖 105001,105002", name = "testItemCodes")
                                 @RequestParam(value = "testItemCodes", required = false) String testItemCodes) {
        List list = testresultService.resultAvgByDay(idCard, date, testItemCodes);

        Map<String, Object> map = new HashMap<>();
        map.put("bpList", list);
        return new ApiRes(list);
    }

    /**
     * 根据idCard查询血糖信息
     */
    @ApiOperation(value = "血糖信息", notes = "血糖信息")
    @RequestMapping(value = "/BgInfo", method = RequestMethod.POST)
    @ResponseBody
    public ApiRes BsInfo(@ApiParam(required = true, value = "身份证号", name = "idCard")
                         @RequestParam("idCard") String idCard,
                         PageParam pageParam) {
        TestresultEntity fbgEntity = testresultService.queryLastBg(idCard, 105001);
        TestresultEntity pbgEntity = testresultService.queryLastBg(idCard, 105002);
        //趋势图所需的空腹、餐后血糖数据
        List<TestresultEntity> fbgList = testresultService.queryBgList(idCard, 105001, pageParam);
        List<TestresultEntity> pbgList = testresultService.queryBgList(idCard, 105002, pageParam);
        PatientInfoVo patientInfoVo = ppPatientBaseService.searchByIdCard(idCard);

        Map<String, Object> map = new HashMap<>();
        if (fbgEntity != null) {
            map.put("fbgValue", fbgEntity.getTestValue() == null ? "" : fbgEntity.getTestValue());
        } else {
            map.put("fbgValue", "");
        }
        if (pbgEntity != null) {
            map.put("pbgValue", pbgEntity.getTestValue() == null ? "" : pbgEntity.getTestValue());
        } else {
            map.put("pbgValue", "");
        }
        map.put("fbgList", fbgList);
        map.put("pbgList", pbgList);
        map.put("bgInfo", patientInfoVo != null ? patientInfoVo.getBsComplication() : "");
        map.put("bgType", patientInfoVo != null ? patientInfoVo.getBsType() : "");
        return new ApiRes(true, map, "", "");
    }

    /**
     * 根据idCard查询血糖报告
     */
    @ApiOperation(value = "血糖报告", notes = "血糖报告")
    @RequestMapping(value = "/BgReport", method = RequestMethod.POST)
    @ResponseBody
    public ApiRes BgReport(@ApiParam(required = true, value = "身份证号", name = "idCard")
                           @RequestParam("idCard") String idCard,
                           @ApiParam(value = "起始时间", name = "beginTime")
                           @RequestParam(value = "beginTime", required = false) String beginTime,
                           @ApiParam(value = "截止时间", name = "endTime")
                           @RequestParam(value = "endTime", required = false) String endTime,
                           PageParam pageParam) {

        //列表所需的空腹、餐后血糖数据
        List<TestresultEntity> list = testresultService.searchBgList(idCard, 105, beginTime, endTime, pageParam);
        int total = testresultService.countBgList(idCard, 105, beginTime, endTime);

        Map<String, Object> map = new HashMap<>();
        map.put("list", list);
        map.put("iTotalDisplayRecords", total);
        return new ApiRes(true, map, "", "");
    }

    /**
     * 根据idCard查询检测报告信息
     */
    @ApiOperation(value = "检测报告信息", notes = "检测报告信息")
    @RequestMapping(value = "/recordInfo", method = RequestMethod.POST)
    @ResponseBody
    public ApiRes recordInfo(@ApiParam(required = true, value = "身份证号", name = "idCard")
                             @RequestParam("idCard") String idCard,
                             @ApiParam(value = "检测项目编号", name = "testKindCode")
                             @RequestParam(value = "testKindCode", required = false) String testKindCode,
                             @ApiParam(value = "起始时间", name = "beginTime")
                             @RequestParam(value = "beginTime", required = false) String beginTime,
                             @ApiParam(value = "截止时间", name = "endTime")
                             @RequestParam(value = "endTime", required = false) String endTime,
                             PageParam pageParam) {

        List<RecordInfoVo> list = testresultService.queryRecord(idCard, testKindCode, beginTime, endTime, pageParam);
        if (list != null) {
            for (RecordInfoVo vo : list) {
                vo.setTestPerson("-");
                if (vo.getDataType() != null && vo.getDataType() == 20) {
                    vo.setSource("输入");
                } else {
                    vo.setSource("设备");
                }
            }
        }
        int total = testresultService.countRecord(idCard, testKindCode, beginTime, endTime);
        Map<String, Object> map = new HashMap<>();
        map.put("list", list);
        map.put("iTotalDisplayRecords", total);
        return new ApiRes(true, map, "", "");
    }

    /**
     * 跳转至病人信息修改页面
     */
    @ApiOperation(value = "病人信息修改页面", notes = "病人信息修改页面")
    @RequestMapping(value = "/toUpdatePatient", method = RequestMethod.GET)
    public String toUpdatePatient(@ApiParam(required = true, name = "id", value = "病人id")
                                  @RequestParam("id") String id, Model model) {
        PpPatientBaseEntity entity = ppPatientBaseService.queryObject(Integer.valueOf(id));
        model.addAttribute("entity", entity);
        return "admin/archives/updatePatient";
    }

    /**
     * 跳转至病人信息修改页面-钱湖
     */
    @ApiOperation(value = "病人信息修改页面-钱湖", notes = "病人信息修改页面-钱湖")
    @RequestMapping(value = "/qianhu/toUpdatePatient", method = RequestMethod.GET)
    public String toUpdateQianhuPatient(@ApiParam(required = true, name = "id", value = "病人id")
                                        @RequestParam("id") String id, Model model) {
        PpPatientBaseEntity entity = ppPatientBaseService.queryObject(Integer.valueOf(id));
        model.addAttribute("entity", entity);
        return "bus/boneLoose/qianhu/updatePatient";
    }

    /**
     * 修改病人信息
     */
    @ApiOperation(value = "修改病人信息", notes = "修改病人信息")
    @RequestMapping(value = "/updatePatient", method = RequestMethod.POST)
    @ResponseBody
    public ApiRes toUpdatePatient(PpPatientBaseReq entity) throws ReturnException {
        /**
         * todo 血脂和造身份证号被过滤
         */
//        if (StringUtils.isNotEmpty(entity.getIdcard())){
//            IdCardUtil.validate(entity.getIdcard());
//        }

        PpPatientBaseEntity ppPatientBaseEntity = ppPatientBaseService.queryObject(entity.getId());
        if (StringUtils.isEmpty(ppPatientBaseEntity.getDoctor()) && !Constant.ADMIN.equals(ShiroUtils.getUserEntity().getUsername())) {
            HlDoctorEntity hlDoctorEntity = hlDoctorService.queryByUserId(ShiroUtils.getUserId());
            entity.setDoctorId(hlDoctorEntity.getId());
            entity.setHospitalId(hlDoctorEntity.getHospId());
        }
        ppPatientBaseService.update(entity);

        /**
         * 病人最后一次数据回显
         */
        PatientDataEntity data = new PatientDataEntity();
        data.setHeight(entity.getHeight().toString());
        data.setWeight(entity.getWeight().toString());
        data.setWaist(entity.getWaist());
        data.setIdCard(entity.getIdcard());
        data.setUpdateTime(new Date());
        data.setSpecRemark(entity.getSpecRemark()); // 特殊处理备注
        if (StrUtil.isNotBlank(entity.getSpecRemark())) {
            // 特殊处理患者
            data.setSpecStatus(SpecStatusEnum.SPEC.getCode());
        } else {
            // 普通处理患者
            data.setSpecStatus(SpecStatusEnum.NORMAL.getCode());
        }
        patientDataService.saveOrUpdate(data);
        return ApiRes.SUCCESS;
    }

    /**
     * 修改患者数据的特殊处理备注
     */
    @ApiOperation(value = "修改患者数据的特殊处理备注", notes = "修改患者数据的特殊处理备注")
    @RequestMapping(value = "/updateSpecRemark", method = RequestMethod.POST)
    @ResponseBody
    public ApiRes updateSpecRemark(PatientDataSpecReq entity) throws ReturnException {

        if (StrUtil.isBlank(entity.getIdcard())) {
            return new ApiRes(false, null, null, "身份证号不能为空。");
        }

        PatientDataEntity data = PatientDataEntity.builder()
                .idCard(entity.getIdcard())
                .updateTime(new Date())
                .specRemark(entity.getSpecRemark())
                .specStatus(StrUtil.isNotBlank(entity.getSpecRemark()) ? SpecStatusEnum.SPEC.getCode() : SpecStatusEnum.NORMAL.getCode())
                .build();
        Boolean flag = patientDataService.updateSpecRemark(data);
        if (flag) {
            return ApiRes.SUCCESS;
        } else {
            return ApiRes.ERROR;
        }
    }

    @ApiOperation(value = "根据身份证号，分页查询特殊处理备注")
    @RequestMapping(value = "/specRemark/list", method = RequestMethod.POST)
    @ResponseBody
    public ApiRes specList(PatientDataSpecEntity entity, PageParam pageParam) {
        List<PatientDataSpecEntity> list = patientDataSpecService.listSpecByIdCard(entity, pageParam);
        Integer count = patientDataSpecService.countSpecByIdCard(entity);
        Map<String, Object> map = new HashMap<>();
        map.put("list", list);
        map.put("iTotalDisplayRecords", count);
        return new ApiRes(true, map, "", "");
    }

    /**
     * 新增患者数据的特殊处理备注
     */
    @ApiOperation(value = "新增患者数据的特殊处理备注", notes = "新增患者数据的特殊处理备注")
    @RequestMapping(value = "/specRemark/add", method = RequestMethod.POST)
    @ResponseBody
    public ApiRes addPatientDataSpecRemark(PatientDataSpecEntity entity) {
        if (StrUtil.isBlank(entity.getIdCard())) {
            return ApiRes.ERROR;
        }
        patientDataSpecService.save(entity);
        return ApiRes.SUCCESS;
    }

    /**
     * 根据id，修改患者数据的特殊处理备注
     */
    @ApiOperation(value = "根据id，修改患者数据的特殊处理备注", notes = "根据id，修改患者数据的特殊处理备注")
    @RequestMapping(value = "/specRemark/updateById", method = RequestMethod.POST)
    @ResponseBody
    public ApiRes updateSpecRemarkById(PatientDataSpecEntity entity) {
        if (null == entity.getId()) {
            return ApiRes.ERROR;
        }
        entity.setUpdateTime(new Date());
        patientDataSpecService.update(entity);
        return ApiRes.SUCCESS;
    }

    /**
     * 根据ids，批量删除患者数据的特殊处理备注内容
     */
    @ApiOperation(value = "根据ids，批量删除患者数据的特殊处理备注内容", notes = "根据ids，批量删除患者数据的特殊处理备注内容")
    @RequestMapping(value = "/specRemark/deleteByIds", method = RequestMethod.POST)
    @ResponseBody
    public ApiRes deleteSpecRemarkByIds(String ids, String idCard) {
        if (StrUtil.isBlank(ids)) {
            return ApiRes.ERROR;
        }
        if (StrUtil.isBlank(idCard)) {
            return ApiRes.ERROR;
        }
        Boolean result = patientDataSpecService.batchDeleteSpecRemarks(ids, idCard);
        return result ? ApiRes.SUCCESS : ApiRes.ERROR;
    }

    /**
     * 跳转至特殊处理新增页面
     */
    @ApiOperation(value = "特殊处理新增页面", notes = "特殊处理新增页面")
    @RequestMapping(value = "/toAddPatientSpecRemark", method = RequestMethod.GET)
    public String toAddSpecRemark() {
        return "admin/archives/addPatientSpec";
    }

    /**
     * 跳转至特殊处理更多页面
     */
    @ApiOperation(value = "特殊处理更多页面", notes = "特殊处理更多页面")
    @RequestMapping(value = "/toMoreSpecRemark", method = RequestMethod.GET)
    public String toMoreSpecRemark() {
        return "admin/archives/moreSpecRemark";
    }

    /**
     * 跳转至特殊处理修改页面
     */
    @ApiOperation(value = "特殊处理修改页面", notes = "特殊处理修改页面")
    @RequestMapping(value = "/toUpdateSpecRemark", method = RequestMethod.GET)
    public String toUpdateCheck() {
        return "admin/archives/updateSpecRemark";
    }

    /**
     * 跳转至血压信息修改页面
     */
    @ApiOperation(value = "血压信息修改页面", notes = "血压信息修改页面")
    @RequestMapping(value = "/toUpdateBpInfo", method = RequestMethod.GET)
    public String toUpdateBpInfo(@ApiParam(required = true, name = "id", value = "病人id")
                                 @RequestParam("id") String id, Model model) {
        PpPatientBaseEntity entity = ppPatientBaseService.queryObject(Integer.valueOf(id));
        model.addAttribute("entity", entity);
        return "admin/archives/updateBpInfo";
    }

    /**
     * 修改血压信息
     */
    @ApiOperation(value = "修改血压信息", notes = "修改血压信息")
    @RequestMapping(value = "/updateBpInfo", method = RequestMethod.POST)
    @ResponseBody
    public ApiRes updateBpInfo(
            @ApiParam(required = true, name = "id", value = "病人id") @RequestParam("id") Integer id,
            @ApiParam(name = "bpType", value = "血压类型") @RequestParam(value = "bpType", required = false) Integer bpType,
            @ApiParam(name = "bpComplication", value = "高血压并发症") @RequestParam(value = "bpComplication", required = false) String bpComplication,
            @ApiParam(name = "smoke", value = "是否吸烟 1:是 2:否") @RequestParam(value = "smoke", required = false) Integer smoke,
            @ApiParam(name = "drink", value = "是否饮酒 1:是 2:否") @RequestParam(value = "drink", required = false) Integer drink,
            @ApiParam(name = "physical", value = "是否为体力劳动者 1:是 2:否") @RequestParam(value = "physical", required = false) Integer physical,
            @ApiParam(name = "highestBpSystolic", value = "最高血压值（高压）（收缩压）") @RequestParam(value = "highestBpSystolic", required = false) String highestBpSystolic,
            @ApiParam(name = "highestBpDiastolic", value = "最高血压值（低压）（舒张压）") @RequestParam(value = "highestBpDiastolic", required = false) String highestBpDiastolic,
            @ApiParam(name = "bpTestPlace", value = "最高血压值-测量地点类型（1-诊室；2-家庭自测）") @RequestParam(value = "bpTestPlace", required = false) Integer bpTestPlace
    ) {
        PpPatientBaseEntity entity = new PpPatientBaseEntity();
        entity.setId(id);
        entity.setBpType(bpType);
        entity.setBpComplication(bpComplication);
        entity.setSmoke(smoke);
        entity.setDrink(drink);
        entity.setPhysical(physical);
        entity.setHighestBpSystolic(highestBpSystolic);
        entity.setHighestBpDiastolic(highestBpDiastolic);
        entity.setBpTestPlace(bpTestPlace);
        entity.setUpdatedtime(new Date());
        ppPatientBaseService.updateBpInfo(entity);
        return ApiRes.SUCCESS;
    }

    /**
     * 跳转至血压信息新增页面
     */
    @ApiOperation(value = "血压信息新增页面", notes = "血压信息新增页面")
    @RequestMapping(value = "/toAddBpInfo", method = RequestMethod.GET)
    public String toAddBpInfo() {
        return "admin/archives/addBpInfo";
    }

    @ApiOperation(value = "新增血压信息", notes = "新增血压信息")
    @RequestMapping(value = "/addBpInfo", method = RequestMethod.POST)
    @ResponseBody
    public ApiRes addBpInfo(@ApiParam(required = true, name = "idCard", value = "身份证号")
                            @RequestParam("idCard") String idCard,
                            @ApiParam(required = true, name = "szyValue", value = "舒张压")
                            @RequestParam("szyValue") Double szyValue,
                            @ApiParam(required = true, name = "ssyValue", value = "收缩压")
                            @RequestParam("ssyValue") Double ssyValue,
                            @ApiParam(required = true, name = "heartRate", value = "心率")
                            @RequestParam("heartRate") Double heartRate,
                            @DateTimeFormat(pattern = DateUtils.DATE_TIME_PATTERN)
                            @ApiParam(required = true, name = "testTime", value = "检测时间")
                            @RequestParam("testTime") Date testTime) {
        TestresultEntity entity = new TestresultEntity();
        entity.setTestTime(testTime);
        entity.setIdCard(idCard);
        entity.setTestKindCode("104");
        entity.setTestKindName("血压");
        entity.setDataType(20);
        entity.setIsPublish(1);
        entity.setCreateTime(new Date());

        entity.setTestItemCode("104001");
        entity.setTestItemName("收缩压");
        entity.setTestValue(String.valueOf(ssyValue));
        testresultService.save(entity);

        entity.setTestItemCode("104002");
        entity.setTestItemName("舒张压");
        entity.setTestValue(String.valueOf(szyValue));
        testresultService.save(entity);

        entity.setTestItemCode("104003");
        entity.setTestItemName("周期脉搏");
        entity.setTestValue(String.valueOf(heartRate));
        testresultService.save(entity);

        /**
         * 病人最后一次数据回显
         */
        PatientDataEntity data = new PatientDataEntity();
        data.setIdCard(entity.getIdCard());
        data.setHighPressure(String.valueOf(ssyValue));
        data.setLowPressure(String.valueOf(szyValue));
        data.setHeartRate(String.valueOf(heartRate));
        data.setUpdateTime(new Date());
        patientDataService.saveOrUpdate(data);
        return ApiRes.SUCCESS;
    }

    /**
     * 跳转至血压信息更多页面
     */
    @ApiOperation(value = "血压信息更多页面", notes = "血压信息更多页面")
    @RequestMapping(value = "/toMoreBpInfo", method = RequestMethod.GET)
    public String toMoreBpInfo() {
        return "admin/archives/moreBpInfo";
    }

    /**
     * 跳转至血糖信息修改页面
     */
    @ApiOperation(value = "血糖信息修改页面", notes = "血糖信息修改页面")
    @RequestMapping(value = "/toUpdateBgInfo", method = RequestMethod.GET)
    public String toUpdateBgInfo(@ApiParam(required = true, name = "id", value = "病人id")
                                 @RequestParam("id") String id, Model model) {
        PpPatientBaseEntity entity = ppPatientBaseService.queryObject(Integer.valueOf(id));
        model.addAttribute("entity", entity);
        return "admin/archives/updateBgInfo";
    }

    /**
     * 修改血糖信息
     */
    @ApiOperation(value = "修改血糖信息", notes = "修改血糖信息")
    @RequestMapping(value = "/updateBgInfo", method = RequestMethod.POST)
    @ResponseBody
    public ApiRes updateBgInfo(@ApiParam(required = true, name = "id", value = "病人id")
                               @RequestParam("id") Integer id,
                               @ApiParam(name = "bsComplication", value = "糖尿病并发症")
                               @RequestParam(value = "bsComplication", required = false) String bsComplication,
                               @ApiParam(name = "bsType", value = "糖尿病类型")
                               @RequestParam(value = "bsType", required = false) Integer bsType) {
        PpPatientBaseEntity entity = new PpPatientBaseEntity();
        entity.setId(id);
        entity.setBsComplication(bsComplication);
        entity.setBsType(bsType);
        ppPatientBaseService.update(entity);
        return ApiRes.SUCCESS;
    }

    /**
     * 跳转至血糖信息新增页面
     */
    @ApiOperation(value = "血糖信息新增页面", notes = "血糖信息新增页面")
    @RequestMapping(value = "/toAddBgInfo", method = RequestMethod.GET)
    public String toAddBgInfo() {
        return "admin/archives/addBgInfo";
    }

    /**
     * 新增血糖信息
     */
    @ApiOperation(value = "新增血糖信息", notes = "新增血糖信息")
    @RequestMapping(value = "/addBgInfo", method = RequestMethod.POST)
    @ResponseBody
    public ApiRes addBgInfo(TestresultEntity entity) {
        entity.setTestKindCode("105");
        entity.setTestKindName("血糖");
        entity.setDataType(20);
        entity.setIsPublish(1);
        entity.setCreateTime(new Date());

        if ("105001".equals(entity.getTestItemCode())) {
            entity.setTestItemName("空腹血糖");
        } else if ("105002".equals(entity.getTestItemCode())) {
            entity.setTestItemName("餐后2小时血糖");
        }
        testresultService.save(entity);

        /**
         * 病人最后一次数据回显
         */
        PatientDataEntity data = new PatientDataEntity();
        data.setIdCard(entity.getIdCard());
        data.setBloodSugar(entity.getTestValue());
        data.setUpdateTime(new Date());
        patientDataService.saveOrUpdate(data);
        return ApiRes.SUCCESS;
    }

    /**
     * 跳转至血糖信息更多页面
     */
    @ApiOperation(value = "血糖信息更多页面", notes = "血糖信息更多页面")
    @RequestMapping(value = "/toMoreBgInfo", method = RequestMethod.GET)
    public String toMoreBgInfo() {
        return "admin/archives/moreBgInfo";
    }

    @ApiOperation(value = "血压检测列表查询")
    @RequestMapping(value = {"/patientBpTests", "/n/patientBpTests"}, method = RequestMethod.POST)
    @ResponseBody
    public MsgVo patientBpTests(TestresultVo entity, PageParam pageParam) {
        List list = testresultService.queryPatientBpTests(entity, pageParam);
        int count = testresultService.queryPatientBpTestsCount(entity);
        return new MsgVo(list, count, count, pageParam.getsEcho());
    }

    @ApiOperation(value = "检测报告更多页面", notes = "检测报告更多页面")
    @RequestMapping(value = "/toMoreRecord", method = RequestMethod.GET)
    public String toMoreRecord() {
        return "admin/archives/moreRecord";
    }

    @ApiOperation(value = "检测项目下拉列表", notes = "检测项目下拉列表")
    @RequestMapping(value = "/searchTestKind", method = RequestMethod.POST)
    @ResponseBody
    public ApiRes searchTestKind() {
        List<TestprojectkindEntity> list = testprojectkindService.queryAll();
        return new ApiRes(true, list, "", "");
    }

    @ApiOperation(value = "检测报告详情页面", notes = "检测报告详情页面")
    @RequestMapping(value = "/toRecordDetail", method = RequestMethod.GET)
    public String toRecordDetail() {
        return "admin/archives/recordDetail";
    }

    @ApiOperation(value = "检测报告详情", notes = "检测报告详情")
    @RequestMapping(value = "/recordDetail", method = RequestMethod.POST)
    @ResponseBody
    public ApiRes recordDetail(@ApiParam(required = true, name = "idCard", value = "身份证号")
                               @RequestParam(value = "idCard") String idCard,
                               @ApiParam(required = true, name = "testKindCode", value = "大类编码")
                               @RequestParam(value = "testKindCode") Integer testKindCode,
                               @ApiParam(required = true, name = "testTime", value = "检测时间")
                               @RequestParam(value = "testTime") String testTime) {
        PatientInfoVo patientInfoVo = ppPatientBaseService.searchByIdCard(idCard);
        if (patientInfoVo == null) {
            return new ApiRes(false, null, "", "");
        }
        IdcardInfoExtractorUtil id = new IdcardInfoExtractorUtil(idCard);
        String sex = "男";
        if (StringUtils.isNotEmpty(id.getGender()) && "2".equals(id.getGender())) {
            sex = "女";
        }
        List<TestresultEntity> list = testresultService.queryRecordDetail(idCard, testKindCode, testTime);
        Map<String, Object> map = new HashMap<>();
        map.put("list", list);
        map.put("hospName", patientInfoVo.getHospName());
        map.put("realName", patientInfoVo.getRealname());
        map.put("age", id.getAge());
        map.put("sex", sex);
        return new ApiRes(true, map, "", "");
    }

    /**
     * 新增病人档案
     */
    @ApiOperation(value = "新增病人档案", notes = "新增病人档案")
    @RequestMapping(value = "/addRecord", method = RequestMethod.POST)
    @ResponseBody
    public ApiRes addRecord(PpPatientBaseEntity entity) throws ReturnException {
        // 钱湖医院的不需要判断身份证号
        if (1112075 != ShiroUtils.getUserId() || ShiroUtils.getUserEntity().getRealName().contains("钱湖医院")) {
            //高血脂人群不对身份证验证
            if (entity.getDiseasesType().indexOf("3") == -1) {
                IdCardUtil.validate(entity.getIdcard());
            }

            PpPatientBaseEntity ppPatientBaseEntity = ppPatientBaseService.queryByIdcard(entity.getIdcard());
            if (ppPatientBaseEntity != null) {
                return new ApiRes(false, null, "身份证号已存在", "身份证号已存在");
            }
        }
        if (ShiroUtils.getUserId() != 5) {
            HlDoctorEntity hlDoctorEntity = hlDoctorService.queryByUserId(ShiroUtils.getUserId());
            if (hlDoctorEntity == null) {
                return new ApiRes(false, null, "该账号非医生账号", "该账号非医生账号");
            }
            entity.setDoctorId(hlDoctorEntity.getId());
            entity.setHospitalId(hlDoctorEntity.getHospId());
        }
        entity.setCreatedtime(new Date());
        entity.setUpdatedtime(new Date());
        entity.setSourceType(1);

        ppPatientBaseService.savePatient(entity);
        return ApiRes.SUCCESS;
    }

    /**
     * 跳转至疼痛评估修改页面
     */
    @ApiOperation(value = "疼痛评估修改页面", notes = "疼痛评估修改页面")
    @RequestMapping(value = "/toUpdatePain", method = RequestMethod.GET)
    public String toUpdatePain() {
        return "admin/archives/updatePain";
    }

    /**
     * 查询疼痛程度列表
     */
    @ApiOperation(value = "查询疼痛程度列表", notes = "查询疼痛程度列表")
    @RequestMapping(value = "/searchPain", method = RequestMethod.POST)
    @ResponseBody
    public ApiRes searchPain() {
        List<SysConfigEntity> list = sysConfigService.queryListByName("painLevel");
        return new ApiRes(true, list, "", "");
    }

    /**
     * 修改疼痛程度
     */
    @ApiOperation(value = "修改疼痛程度", notes = "修改疼痛程度")
    @RequestMapping(value = "/updatePain", method = RequestMethod.POST)
    @ResponseBody
    public ApiRes updatePain(@ApiParam(required = true, name = "id", value = "病人id")
                             @RequestParam("id") Integer id,
                             @ApiParam(required = true, name = "painLevel", value = "疼痛程度")
                             @RequestParam("painLevel") Integer painLevel) {
        PpPatientBaseEntity entity = new PpPatientBaseEntity();
        entity.setId(id);
        entity.setPainLevel(painLevel);
        ppPatientBaseService.update(entity);
        return ApiRes.SUCCESS;
    }

    /**
     * 修改疼痛程度
     */
    @ApiOperation(value = "病人最后一次数据", notes = "病人最后一次数据")
    @RequestMapping(value = "/patientData", method = RequestMethod.GET)
    @ResponseBody
    public ApiRes patientData(@ApiParam(required = true, name = "idCard", value = "身份证")
                              @RequestParam("idCard") String idCard) {
        PatientDataEntity data = patientDataService.queryByIdCard(idCard);
        return new ApiRes(data);
    }

    @ApiOperation(value = "根据身份证号，查询最近7天是否未测量过血压/血糖")
    @RequestMapping(value = "/queryNotTestDataSevenDays", method = RequestMethod.POST)
    @ResponseBody
    public ApiRes queryNotTestDataSevenDays(@ApiParam(required = true, name = "idCard", value = "身份证")
                                            @RequestParam("idCard") String idCard) {
        try {
            // 根据身份证号，查询最近7天是否未测量过血压
            boolean notTestBp = patientDataService.queryNotBpTestDataSevenDays(idCard);
            // 根据身份证号，查询最近7天是否未测量过血糖
            boolean notTestBg = patientDataService.queryNotBgTestDataSevenDays(idCard);
            Map<String, Object> map = new HashMap<>();
            map.put("notTestBp", notTestBp);
            map.put("notTestBg", notTestBg);
            return new ApiRes(map);
        } catch (Exception ex) {
            return ApiRes.failure(ex);
        }
    }

    /**
     * 导出
     */
    @GetMapping("/export")
    @ResponseBody
    @ApiOperation("导出")
    public void export(HttpServletResponse response, @ApiParam(value = "1=高血压人群 2=糖尿病人群 3=高血脂人群 4=骨松人群", name = "diseasesType")
                             @RequestParam(value = "diseasesType", required = true) String diseasesType) {
        if (diseasesType.equals("1")){
            PpPatientBaseVo entity = new PpPatientBaseExtVo();
            String ids = hlHospitalService.getChildeIds();
            if (StringUtils.isNotEmpty(ids)) {
                entity.setHospitalIds(ids);
            }

            /*util.exportExcel(list, "info");*/
            File file = null;
            try {

                String xlsxFileName = "血压" + ".xlsx";
                List<bloodPressureExport> list = ppPatientBaseService.querybloodPressureExport(entity);
                ExcelUtil<bloodPressureExport> util = new ExcelUtil<bloodPressureExport>(bloodPressureExport.class);
                AjaxResult ajaxResult = util.exportExcel(list, xlsxFileName);
                String fileName = String.valueOf(ajaxResult.get("msg"));

                // 获取本地 .xlsx 文件的绝对路径
                String filePath = util.getAbsoluteFile(fileName);
                response.reset();

                response.setCharacterEncoding("utf-8");
                response.setContentType("application/octet-stream; charset=UTF-8");
                response.setHeader("Content-Disposition", "attachment;filename=" + new String(xlsxFileName.getBytes("utf-8"), "ISO8859-1"));
                FileUtils.writeBytes(filePath, response.getOutputStream());
            } catch (Exception e) {

            }
        }else if (diseasesType.equals("2")){
            PpPatientBaseVo entity = new PpPatientBaseExtVo();
            String ids = hlHospitalService.getChildeIds();
            if (StringUtils.isNotEmpty(ids)) {
                entity.setHospitalIds(ids);
            }

            /*util.exportExcel(list, "info");*/
            File file = null;
            try {

                String xlsxFileName = "血糖" + ".xlsx";
                List<bloodSugarExport> list = ppPatientBaseService.querybloodSugarExport(entity);
                ExcelUtil<bloodSugarExport> util = new ExcelUtil<bloodSugarExport>(bloodSugarExport.class);
                AjaxResult ajaxResult = util.exportExcel(list, xlsxFileName);
                String fileName = String.valueOf(ajaxResult.get("msg"));

                // 获取本地 .xlsx 文件的绝对路径
                String filePath = util.getAbsoluteFile(fileName);
                response.reset();

                response.setCharacterEncoding("utf-8");
                response.setContentType("application/octet-stream; charset=UTF-8");
                response.setHeader("Content-Disposition", "attachment;filename=" + new String(xlsxFileName.getBytes("utf-8"), "ISO8859-1"));
                FileUtils.writeBytes(filePath, response.getOutputStream());
            } catch (Exception e) {

            }
        }else {
            AjaxResult.error("不是高血压，糖尿病人群");
        }
    }

    @ApiOperation(value = "骨松档案病人的excel导入")
    @RequestMapping(value = "/excel/import/bl", method = RequestMethod.POST)
    @ResponseBody
    public ApiRes excelBLImport(@RequestParam("file") MultipartFile file) throws Exception {

        Long userId = null;
        Long doctorId = null;
        Long hospitalId = null;
        try {
            userId = ShiroUtils.getUserId();
        } finally {
        }

        if (UserConsts.cxxp_user_id.equals(userId)) {
            //慈溪新浦医院
            doctorId = UserConsts.cxxp_doctor_id;
            hospitalId = UserConsts.cxxp_hospital_id;

        } else if (UserConsts.qh_user_id.equals(userId)) {
            //鄞州区钱湖医院
            doctorId = UserConsts.qh_doctor_id;
            hospitalId = UserConsts.qh_hospital_id;

        }


        ExcelUtil<PpPatientBaseEntity> util = new ExcelUtil<PpPatientBaseEntity>(PpPatientBaseEntity.class);
        List<PpPatientBaseEntity> userList = util.importExcel(file.getInputStream());
        for (PpPatientBaseEntity ppPatientBaseEntity : userList) {
            if (com.healthcloud.utils.StringUtils.isNotEmpty(ppPatientBaseEntity.getIdcard())) {

                IdcardInfoExtractorUtil id = new IdcardInfoExtractorUtil(ppPatientBaseEntity.getIdcard());
                ppPatientBaseEntity.setCreatedtime(new Date());
                ppPatientBaseEntity.setUpdatedtime(new Date());
                ppPatientBaseEntity.setDoctorId(doctorId);
                ppPatientBaseEntity.setHospitalId(hospitalId);

                ppPatientBaseEntity.setGender(Integer.valueOf(id.getGender()));

                try {
                    PpPatientBaseEntity p = ppPatientBaseService.queryByIdcard(ppPatientBaseEntity.getIdcard());
                    //判空，防止重复导入
                    if (p == null) {
                        ppPatientBaseService.savePatientTemp(ppPatientBaseEntity);
                    }
                } finally {
                }
            }
        }

        return ApiRes.success();
    }


    /**
     * 失智模块-修改病人信息页面跳转接口
     *
     * @return
     */
    @ApiOperation("跳转至病人信息修改页面")
    @GetMapping("/new/update")
    public String loseWisdomPatient(@ApiParam(required = true, name = "id", value = "病人id")
                                    @RequestParam("id") String id, Model model) {

        PpPatientBaseEntity entity = ppPatientBaseService.queryObject(Integer.valueOf(id));
        model.addAttribute("entity", entity);
        return "/bus/pppatientbase/update";
    }

    @RequiresPermissions("patient:update:idCard")
    @ApiOperation("修改病人身份证号")
    @GetMapping("/update/idCard")
    public String toUpdateIdCard() {
        return "/bus/pppatientbase/updateIdCard";
    }

    @ApiOperation("修改病人身份证号")
    @PostMapping("/update/idCard")
    @ResponseBody
    public ApiRes updateIdCard(@RequestParam(name = "oldIdCard") String oldIdCard,
                               @RequestParam(name = "newIdCard") String newIdCard) {
        if (com.healthcloud.utils.StringUtils.isEmpty(oldIdCard) || com.healthcloud.utils.StringUtils.isEmpty(newIdCard)) {
            return ApiRes.failure("请输入身份证号。");
        }

        PpPatientBaseEntity ppPatientBaseEntity = ppPatientBaseService.queryByIdcard(newIdCard);
        if (com.healthcloud.utils.StringUtils.isNotNull(ppPatientBaseEntity)) {
            return ApiRes.failure("身份证号【" + newIdCard + "】已存在。");
        }
        ppPatientBaseService.updateIdCard(oldIdCard, newIdCard);
        return ApiRes.success();
    }
}
